#pragma once
#include<pthread.h>
#include<iostream>

namespace MutexModule
{
    class  Mutex
    {
    public:
        //避免死锁或者对一份资源多次释放
        Mutex(const Mutex&) = delete;
        const Mutex& operator = (const Mutex&) = delete;
        Mutex()
        {
            int n=pthread_mutex_init(&_mutex,nullptr);
            if(n!=0)
            {
                std::cout<<"初始化锁错误！"<<std::endl;
            }
        }
        ~Mutex()
        {
            int n=pthread_mutex_destroy(&_mutex);
            if(n!=0)
            {
                std::cout<<"销毁锁错误！"<<std::endl;
            }
        }
        void Lock()
        {
            int n=pthread_mutex_lock(&_mutex);
            if(n!=0)
            {
                std::cout<<"加锁错误！"<<std::endl;
            }
        }
        void Unlock()
        {
            int n=pthread_mutex_unlock(&_mutex);
            if(n!=0)
            {
                std::cout<<"解锁错误！"<<std::endl;
            }
        }
        pthread_mutex_t* Ptr()
        {
            return &_mutex;
        }
    private:
    pthread_mutex_t _mutex;    
    };

    class LockGuard
    {
    public:
        LockGuard(Mutex &mtx):_mtx(mtx)
        {
            _mtx.Lock();
        }
        ~LockGuard()
        {
            _mtx.Unlock();
        }
    private:
        Mutex &_mtx;// 必须为引用<---Mutex拷贝被禁止
    };

}